package com.lzl.api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lzl.util.WebUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.lzl.util.JacksonUtil;

import java.util.HashMap;
import java.util.Map;

/** 
 *  
* @ClassName: LogAspect  
* @Description: 日志记录AOP实现  
* @author  
* @date 2016年05月3日 下午1:51:59  
* 
 */
@Aspect
@Component  
public class LogAspect {
    private final Logger        logger          = LogManager.getLogger(this.getClass());
    
    /**session一次有效时间***/
    private static final Long validTime = 30*24*60*60*1000l;//一个月
    
    public static final String MEMBERID = "MEMBERID";

    ThreadLocal<Long> startTime  = new ThreadLocal<Long>();
    
    @Pointcut("execution(* com.lzl.api.controller..*.*(..))")
    public void webLog(){}
    
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = "";
        if("GET".equals(method)){
//        	queryString = request.getQueryString();
            Map map = WebUtil.getParamMap(request);
            queryString = map.toString();
            request.setAttribute("QUERYMAP", map);
        }else{
            Object[] paramsArray = joinPoint.getArgs();
            queryString = argsArrayToString(paramsArray);
        }
         
        // 去掉最后一个空格  
        // 省略日志记录内容
        logger.info("请求开始, 各个参数   "+queryString);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
        logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    }

    
    /**
     * 获取登录用户远程主机ip地址
     * 
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    private String argsArrayToString(Object[] paramsArray) throws Exception {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if(paramsArray[i] == null || paramsArray[i] instanceof HttpServletRequest || paramsArray[i] instanceof HttpServletResponse || paramsArray[i] instanceof MultipartFile){
                    continue;
                }
                params += JacksonUtil.obj2json(paramsArray[i]) + " ";
                break;
            }
        }
        return params.trim();
    }
}